<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUpdateAvaService } from '@/api/user'

// loading 效果
const loading = ref(false)
// 给 imgUrl 一个初始值
const store = useUserStore()

const uploadRef = ref()

const imgUrl = ref(store.user.user_pic)
// 选择图片预览
const handleChange = (file) => {
  const reader = new FileReader()
  // 将图片转为base64格式
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}

// 上传图片
const upload = async () => {
  loading.value = true
  await userUpdateAvaService(imgUrl.value)
  await store.getUserInfo()
  loading.value = false
  ElMessage.success('更换头像成功')
}
</script>
<template>
  <page-container title="更换头像">
    <el-upload
      v-loading="loading"
      element-loading-text="拼命加载中..."
      ref="uploadRef"
      class="avatar-uploader"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleChange"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <br />
    <el-button
      type="primary"
      @click="uploadRef.$el.querySelector('input').click()"
      :icon="Plus"
      size="large"
      >选择图片</el-button
    >
    <el-button @click="upload" type="success" :icon="Upload" size="large"
      >上传头像</el-button
    >
  </page-container>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
